﻿using DevExpress.Images;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Linq;
using System.Windows.Forms;

namespace Inaction.UI.Extensions.ControlExtensions.Grid
{
    internal class ChangeCaptionHelper
    {
        public static void Extend(GridView gridView)
        {
            gridView.PopupMenuShowing += new PopupMenuShowingEventHandler(gridView_PopupMenuShowing);
        }

        static void gridView_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            if (e.HitInfo.Column == null) return;
            var view = sender as GridView;
            if (view == null) return;
            var itemCaption = e.Menu.Items.Cast<DevExpress.Utils.Menu.DXMenuItem>().FirstOrDefault(p => p.Caption == "修改标题");
            if (itemCaption == null)
            {
                itemCaption = new DevExpress.Utils.Menu.DXMenuItem("修改标题");
                itemCaption.Image = Properties.Resources.Modify;
                itemCaption.Tag = e.HitInfo.Column;
                e.Menu.Items.Insert(0, itemCaption);
                itemCaption.Click += new EventHandler(ChangeCaption_Click);
            }
            itemCaption.Visible = e.HitInfo.InColumn;
        }

        static void ChangeCaption_Click(object sender, EventArgs e)
        {
            var item = sender as DevExpress.Utils.Menu.DXMenuItem;
            var column = item.Tag as DevExpress.XtraGrid.Columns.GridColumn;
            var f = new Grid.ChangeCaptionForm(column.Caption);
            if (f.ShowDialog() == DialogResult.Yes)
            {
                column.Caption = f.Caption;
            }
        }
    }
}
